/**
 * Created by Joe on 2017/7/5 0005.
 */

var Partner = {
    fields: {
        selects: ["sales", "accoutPeriod", "star"], //下拉框
        radios: [],//单选框
        checkboxs: [],//复选款
        textareas: [],//多行文本框
        selfDefine: [{"field": "metroLine ", "selector": "a.metro_line"}]
    }
};
$(document).ready(function () {
    initDataTables();
    handleEvent();
    /** init baidu uploader*/
    console.log("type of  Uploader", typeof(Uploader));
    console.log("typeof(Uploader) == 'undefined'", typeof(Uploader) == 'undefined');

    if (typeof(Uploader) !== 'undefined') {
        Uploader.initUploader(Uploader.server.company_bm_images);
    }
});

function initDataTables() {
    var table = $('.dataTable').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
}


function handleEvent() {

    $('#new-company-form').on('click', '#uploader-bm', function (e) {
        $('#filePicker input[name=file]').click();
        Uploader.target_alert = "new-company-form";
        Uploader.target_server = Uploader.server.company_bm_images;
    });

    $('#new-company-form').on('click', '#uploader-am', function (e) {
        $('#filePicker input[name=file]').click();
        Uploader.target_alert = "new-company-form";
        Uploader.target_server = Uploader.server.company_am_images;
    });

    $('#new-company-form').on('click', '#uploader-cm', function (e) {
        $('#filePicker input[name=file]').click();
        Uploader.target_alert = "new-company-form";
        Uploader.target_server = Uploader.server.company_cm_images;
    });

    $('.btn-partner-audit').on('click', function () {
        layer.alert('审核通过成功', {
            skin: 'layui-layer-molv',
            title: '提示信息'
            , closeBtn: 0
            , anim: 4 //动画类型
        });
    });
    $('#DataTables_partner_readonly').on('click', ".btn-detail", function () {
        Utils.formReadOnly("#company-detail-form");
        requestDetail($(this).siblings("input").val());
    });

    $("#query-company").click(function () {
        var companyName = $("#companyName").val();
        if ($.trim(companyName) == null || $.trim(companyName) == '') {
            alerts("query-company-form", 2, "请输入查询条件");
            return;
        } else {
            var url = /*[[@{/queryCompany}]]*/ 'queryCompany';
            $("#DataTables_partner").DataTable().rows().remove().draw();
            requestQueryByName(0, url, "#DataTables_partner");
        }
    });

    $("#query-company-auditing").click(function () {
        var companyName = $("#companyName").val();
        if ($.trim(companyName) == null || $.trim(companyName) == '') {
            alerts("query-company-form", 2, "请输入查询条件");
            return;
        } else {
            var url = /*[[@{/findAuditingCompany}]]*/ 'findAuditingCompany';
            $("#DataTables_partner_audit").DataTable().rows().remove().draw();
            requestQueryByName(1, url, "#DataTables_partner_audit");
        }
    });

    $("#query-company-readOnly").click(function () {
        var companyName = $("#companyName").val();
        if ($.trim(companyName) == null || $.trim(companyName) == '') {
            alerts("query-company-form", 2, "请输入查询条件");
            return;
        } else {
            var url = /*[[@{/queryCompany}]]*/ 'queryCompany';
            $("#DataTables_partner_readonly").DataTable().rows().remove().draw();
            requestQueryByName(2, url, "#DataTables_partner_readonly");
        }
    });

    $("#DataTables_partner_audit").on("click", ".btn-preview", function () {
        var imageUrl = $(this).attr("data");
        Utils.preview(imageUrl);
    });
    $("#DataTables_partner").on("click", ".btn-preview", function () {
        var imageUrl = $(this).attr("data");
        Utils.preview(imageUrl);
    });
    $("#DataTables_partner_readonly").on("click", ".btn-preview", function () {
        var imageUrl = $(this).attr("data");
        Utils.preview(imageUrl);
    });
    $(".btn-preview").click(function () {
        var imageUrl = $(this).prev().attr("src");
        Utils.preview(imageUrl);
    });
    $(".btn-preview-win").click(function () {
        var imageUrl = $(this).prev().val();
        Utils.preview(imageUrl);
    });

    $('#DataTables_partner_audit').on('click', ".btn-audit-success", function () {
        var applyId = $(this).attr("data");
        requestDetail($(this).siblings("input").val(), applyId);
    });

    $('#DataTables_partner_audit').on('click', ".btn-audit-fail", function () {
        var applyId = $(this).attr("data");
        $("#audit-fail-form").find("input[name='applyId']").val(applyId);
        $("#audit-fail-modal").modal("toggle");
    });

    $('#btn-add-company').on('click', function () {
        Utils.clearForm("#new-company-form");
        $("#partner-company-modal").modal("toggle");

    });

    $('.btn-cancel-new').on('click', function () {
        $("#partner-company-modal").modal("toggle");
    });

    $('.btn-save-new').on('click', function () {
        requestSaveNew();
    });

    $('.cancel-audit-success').on('click', function () {
        $("#partner-detail-modal").modal("toggle");
    });
    $('.cancel-audit-fail').on('click', function () {
        $("#audit-fail-modal").modal("toggle");
    });
    $('.save-audit-success').on('click', function () {
        requestAuditSuccess();
    });
    $('.save-audit-fail').on('click', function () {
        requestAuditFail();
    });
    /** delete by id **/
    $('#DataTables_partner').on('click', '.btn-detail-delete', function () {
        //delete tr row
        var $tr = $(this).parents('tr');
        var row = $('#DataTables_partner').DataTable().row($tr);
        var url = /*[[@{/removeBy}]]*/ 'removeBy';
        Utils.ajaxSubmit(url + "/" + $(this).siblings("input").val(), {}, function (data) {
            if (data.result == "success") {
                row.remove().draw();
                layer.msg('公司已删除', {time: 3000, icon: 6});
            }
            if (data.result == "fail") {
                Utils.errorAlert(data.result.errorMessage);
            }
        });
    });

}

function requestQueryByName(type, url, targetEle) {
    var companyName = $("#companyName").val();
    Utils.ajaxSubmit(url + "/" + companyName, {}, function (data) {
        console.log("data ： ", data);
        if (data.result == "success") {
            if (type == 0) {
                addTableRow(data.content, targetEle);
            } else if (type == 1) {
                addTableRowAuditing(data.content, targetEle);
            } else if (type == 2) {
                addTableRowRead(data.content, targetEle);
            }
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

/**添加table行*/
function addTableRowAuditing(companyList, targetEle) {
    $.each(companyList, function (k, v) {
        var btnRemoveEle = '<input type="hidden" value="' + v.id + '">';
        btnRemoveEle = btnRemoveEle.concat('<a class="btn btn-primary btn-audit-success" data="'+v.applyId+'">审核通过</a>');
        btnRemoveEle = btnRemoveEle.concat('&nbsp;&nbsp;&nbsp;<a class="btn btn-primary btn-audit-fail" data="'+v.applyId+'">审核不通过</a>');
        $(targetEle).dataTable().fnAddData([v.companyName, v.companyLaw, v.tel, v.address, getImageTD(v.businesslicManagerUrl),
            getImageTD(v.authorizationManagerUrl), getImageTD(v.cardManagerUrl), btnRemoveEle]);
    });
}

/**添加table行*/
function addTableRow(companyList, targetEle) {
    var url = /*[[@{//partner/detail/}]]*/ '/partner/detail/';
    $.each(companyList, function (k, v) {
        url = url.concat(v.id);
        addTableSingleRow(url, v, targetEle);
    });
}
function addTableSingleRow(url, v, targetEle) {
    var btnRemoveEle = '<input type="hidden" value="' + v.id + '"> <a class="btn btn-primary btn-detail" href="' + url + '">查看明细</a>';
    btnRemoveEle = btnRemoveEle.concat('&nbsp;&nbsp;&nbsp;<a class="btn btn-danger btn-detail-delete">删除</a>');
    $(targetEle).dataTable().fnAddData([v.companyName, v.companyLaw, v.tel, v.address, getImageTD(v.businesslicManagerUrl),
        getImageTD(v.authorizationManagerUrl), getImageTD(v.cardManagerUrl), btnRemoveEle]);
}

/**添加table行*/
function addTableRowRead(companyList, targetEle) {
    $.each(companyList, function (k, v) {
        var btnRemoveEle = '<input type="hidden" value="' + v.id + '"> <a class="btn btn-primary btn-detail" >查看明细</a>';
        $(targetEle).dataTable().fnAddData([v.companyName, v.companyLaw, v.tel, v.address, getImageTD(v.businesslicManagerUrl),
            getImageTD(v.authorizationManagerUrl), getImageTD(v.cardManagerUrl), btnRemoveEle]);
    });
}

function requestSaveNew() {
    var url = /*[[@{/createCompany}]]*/ 'createCompany';
    var param = $("#new-company-form").serialize();
    Utils.ajaxSubmit(url, param, function (data) {
        console.log("data ： ", data);
        if (data.result == "success") {
            $("#partner-company-modal").modal("toggle");
            var detail_url = /*[[@{//partner/detail/}]]*/ '/partner/detail/';
            detail_url = detail_url.concat(data.content.id);
            addTableSingleRow(detail_url, data.content, "#DataTables_partner");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}


function requestDetail(companyId, applyId) {
    console.log("applyId ： ", applyId);
    var url = /*[[@{/getCompanyById}]]*/ 'getCompanyById';
    Utils.clearForm("#company-detail-form");
    Utils.ajaxSubmit(url + "/" + companyId, {}, function (data) {
        console.log("data ： ", data);
        if (data.result == "success") {
            Utils.fillForms(data.content, Partner.fields);
            if (typeof(applyId) !== "undefined") {
                $("#company-detail-form").find("input[name='applyId']").val(applyId);
            }
            $("#businesslicManagerId").attr("src", data.content.businesslicManagerUrl);
            $("#authorizationManagerId").attr("src", data.content.authorizationManagerUrl);
            $("#cardManagerId").attr("src", data.content.cardManagerUrl);
            $("#partner-detail-modal").modal("toggle");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function requestAuditSuccess() {
    var url = /*[[@{/auditingSuccess}]]*/ 'auditingSuccess';
    var params = $("#company-detail-form").serialize();
    Utils.ajaxSubmit(url, params, function (data) {
        console.log("data ： ", data);
        if (data.result == "success") {
            $("#partner-detail-modal").modal("toggle");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function requestAuditFail() {
    var url = /*[[@{/auditingFail}]]*/ 'auditingFail';
    var params = $("#audit-fail-form").serialize();
    Utils.ajaxSubmit(url, params, function (data) {
        console.log("data ： ", data);
        if (data.result == "success") {
            $("#audit-fail-modal").modal("toggle");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function getImageTD(imageUrl) {
    if (imageUrl == null || imageUrl == '') {
        return '暂无图片';
    }
    /* var imageUrl = '<img class="img_td" src="' + imageUrl + '"><a class="btn-preview">查看大图</a>';*/
    var imageUrl = '<a class="btn-preview" data="' + imageUrl + '">查看大图</a>';
    return imageUrl;
}
